#include <FS.h> //ESP设备内置FileSystem,可操作FLASH
#include <ArduinoJson.h>
#include <ESP8266WiFi.h> //可创建WIFI热点
#include <WiFi.h>
#include "state.h"
//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>Wifi
const char *ssid = "Super 80";
const char *password = "";
const char *SSIDFile = "/ssid.json";
void WiFiEvent(WiFiEvent_t event);
void WifiConfig(DynamicJsonDocument &doc) {
    fs::File file = SPIFFS.open(SSIDFile, "w");
    if(file) {
      serializeJson(doc,file);
      file.close();
    }
}
void StartWifiAP() {
    WiFi.softAP(ssid, password);
}
void ConnectWifi() {
  String ssid = "6";
  String passwd = "12335678";
  Serial.println("Try to connect WiFi");
  TryConnectWifi(ssid,passwd);
  State = STATE_WIFI_DISCONNECTED;
  if(WiFi.status() != WL_CONNECTED) {
    Serial.println("WiFi not connected");
  } else {
    Serial.println("WiFi connected");
  }
}

int maxRetries = 3;
int retryCount = 0;

void TryConnectWifi(String ssid, String passwd) {
  WiFi.begin(ssid, passwd);
  unsigned long startAttempt = millis();
  while(WiFi.status() != WL_CONNECTED) { // wait for the Wi-Fi to connect
    delay(500);
    if(millis() - startAttempt > 5000) {
      break;
    }
  }
}
void TryReconnectWifi() {
  if (retryCount < maxRetries) {
    Serial.println("Attempting to reconnect...");
    unsigned long startAttempt = millis();
    WiFi.reconnect();
    while(WiFi.status() != WL_CONNECTED) { // wait for the Wi-Fi to connect
      delay(500);
      if(millis() - startAttempt > 5000) {
        break;
      }
    }
    retryCount++;
  } else {
    Serial.println("Max retries reached. Restarting ESP32...");
    ESP.restart();
  }
}